package com.fh.shop.api.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
@Slf4j
public class MailUtil {

    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to, String title, String content) {
        try {
            // 组装邮件内容
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            // 发件人
            mimeMessageHelper.setFrom(from);
            // 收件人
            mimeMessageHelper.setTo(to);
            // 主题
            mimeMessageHelper.setSubject(title);
            // 内容[支持html]
            mimeMessageHelper.setText(content, true);
            // 发送邮件
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("mail send error:"+e.getMessage());
            throw new RuntimeException(e);
        } catch (Exception e) {
            log.error("mail error:"+e.getMessage());
            throw new RuntimeException(e);
        }

    }
}
